package com.baizhi.aspect;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.AdminLogDAO;
import com.baizhi.entity.Admin;
import com.baizhi.entity.AdminLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

//注解式aop
@Configuration//将切面类创建的对象  交给工厂
@Aspect//   声明当前类为切面类  会自动编织切点和增强
public class LogAop {

    @Autowired
    private AdminLogDAO adminLogDAO;
    //@pointCut 声明一个切入点  参数为切入点表达式
    // pointCut下的方法可以随便写 不写具体内容 因为该注解需要加在一个方法上
    //execution 切方法
    //@annotation切注解
    @Pointcut("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logPointCut(){}
    //@Before() 前置增强
    //@After() 后置增强
    //@AfterThrowing 异常增强
    //@Around() 环绕增强
    @After("logPointCut()")
    public void logAfter(JoinPoint joinPoint){
        System.out.println("\"增强方法执行了\" = " + "增强方法执行了");
        //获取日志数据
        AdminLog adminLog = new AdminLog();
        //获取时间
        adminLog.setDate(new Date());
        //从session中获取admin的id
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        //获取request
        HttpServletRequest request = requestAttributes.getRequest();
        //通过request获取session
        HttpSession session = request.getSession();
        //获取作用域存储的对象
        Admin admin = (Admin) session.getAttribute("admin");
//        System.out.println(admin);
        //存储admin的id
        adminLog.setAdminId(admin.getId());
        //调用工具类获取IP地址并存储到对象中
        adminLog.setIp(IPKit.getIpAddrByRequest(request));
        //获取注解的值
//        1.获取方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        2.获取方法对象
        Method method = signature.getMethod();
//        3.获取方法上的注解
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
//        4.获取注解的值
        adminLog.setContent(annotation.content());
        // 获取内容      获取类型
        adminLog.setType(annotation.type());
//        将对象存入到数据库中
        System.out.println("adminLog = " + adminLog);
        adminLogDAO.insertAdminLog(adminLog);
    }

}
